package com.module.app.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Patterns
import android.webkit.URLUtil
import com.module.app.bus.UpdateBus
import com.module.app.ext.updateFlow
import com.module.app.network.getCommonService
import com.module.base.ext.cycleTiming
import com.module.base.ext.download
import com.module.base.utils.FileCommonUtils
import com.module.base.utils.InstallUtil
import com.module.base.utils.ToastUtils
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.module.app.R
import com.module.frame.base.BaseFrameApplication
import com.module.frame.ext.postEvent
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import java.io.File

object UpdateUtils {

    fun update(context: Context, url: String, appVersionName: String) {
        if (FileCommonUtils.getSuffixName(url) != "apk") {
            val isUrl = URLUtil.isValidUrl(url) && Patterns.WEB_URL.matcher(url).matches()
            if (!isUrl) {
                ToastUtils.showShort("下载地址错误")
                return
            }
            val intent = Intent()
            intent.action = "android.intent.action.VIEW"
            val content_url = Uri.parse(url)
            intent.data = content_url
            context.startActivity(intent)
            return
        }
        XXPermissions.with(context)
            .permission(Permission.READ_EXTERNAL_STORAGE)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .request(object : OnPermissionCallback {
                //循环计时的job
                private var cycleTimingJob: Job? = null

                //下载的job
                private var downloadJob: Job? = null
                private var mProgress = 0f
                override fun onGranted(permissions: List<String>, all: Boolean) {
                    if (all) {
                        val path =
                            com.module.app.utils.FileUtils.getApkPath() + File.separator + appVersionName + ".apk" //获取目录
                        //执行下载，作用域域使用的是全局GlobalScope，所以记得及时取消
                        downloadJob = download(path, {
                            postEvent(updateFlow, UpdateBus(0f, com.module.app.bean.IType.STATUS.start))
                            //执行下载
                            getCommonService().download(url)
                        }, {
                            mProgress = it
                        }, {
                            //完成
                            postEvent(updateFlow, UpdateBus(100f, com.module.app.bean.IType.STATUS.end))
                            if (!it.isNullOrEmpty() && it.endsWith(".apk")) {
                                InstallUtil(BaseFrameApplication.getContext(), it).install()
                            } else if (it.isNullOrEmpty()) {
                                ToastUtils.showShortSafe("下载异常")
                            }
                            cycleTimingJob?.cancel()
                            downloadJob?.cancel()
                        }, {
                            //失败
                            postEvent(updateFlow, UpdateBus(100f, com.module.app.bean.IType.STATUS.end))
                            ToastUtils.showShortSafe("下载异常")
                            cycleTimingJob?.cancel()
                            downloadJob?.cancel()
                        })
                        //循环计时
                        //由于在onProgress 回调太快，导致经常出问题。
                        cycleTimingJob = cycleTiming(GlobalScope, 100) {
                            postEvent(updateFlow, UpdateBus(mProgress, com.module.app.bean.IType.STATUS.progress))

                        }
                    }
                }

                override fun onDenied(permissions: List<String>, never: Boolean) {
                    ToastUtils.showLong(R.string.permissions_write_read_never_reject_update)
                }
            })
    }
}